package com.sita.friend.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.colintmiller.simplenosql.DataComparator;
import com.colintmiller.simplenosql.DataFilter;
import com.colintmiller.simplenosql.NoSQL;
import com.colintmiller.simplenosql.NoSQLEntity;
import com.colintmiller.simplenosql.RetrievalCallback;
import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.nostra13.universalimageloader.utils.L;
import com.sita.bike.R;
import com.sita.bike.persistence.TrendMember;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Account;
import com.sita.bike.rest.model.AddRequest;
import com.sita.bike.rest.model.RestResponse;
import com.sita.bike.rest.model.RtResource;
import com.sita.bike.rest.model.request.GetAccountRequest;
import com.sita.bike.rest.model.request.ResourceListByAccountRequest;
import com.sita.bike.rest.model.request.RtBlacklistRequest;
import com.sita.bike.rest.model.response.GetAccountResponse;
import com.sita.bike.rest.model.response.MileageSummaryResponse;
import com.sita.bike.rest.model.response.RtBlacklistResponse;
import com.sita.bike.rest.model.response.RtResourcesList4AccountResponse;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.PersistUtils;
import com.sita.friend.Constant;
import com.sita.friend.FriendHelper;
import com.sita.friend.event.AcceptFriendEvent;
import com.sita.friend.ui.adapter.RtFriendResAdapter;
import com.sita.tboard.ActivityBase;
import com.sita.tboard.global.LocalConstants;
import com.sita.tboard.roadtrust.discovery.RtResourceListFragment;
import com.sita.tboard.ui.activity.ImagePagerActivity;
import com.sita.tboard.ui.event.ReloadRtResourceEvent;
import com.sita.tboard.ui.tools.AudioPlayer;
import com.sita.tboard.util.DateUtils;
import com.sita.tboard.util.LocationUtils;
import com.sita.tboard.util.NumberUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;


/**
 * Created by hongyun on 2015/12/15.
 */
public class FriendDetailActivity extends ActivityBase{


//    private final String KEY_RECYCLER_STATE = "recycler_state";

    private static final int MENU_REMOVE_FRIEND = 1;
    private static final int MENU_ADD_BLACKLIST = 2;
    private static final int MENU_REMOVE_BLACKLIST = 3;

    private String mAccountId;
    private String title;

    private AudioPlayer player;

//    private int currPage = -1;

//    private Bundle mBundleRecyclerViewState;

    private ActionBar actionBar;

    @Bind(R.id.layout_collapse_toolbar)
    CollapsingToolbarLayout collapsingToolbarLayout;
//    @Bind(R.id.title)
//    TextView titleView;
    @Bind(R.id.image_background)
    ImageView mHeaderBackground;
    @Bind(R.id.avatar)
    CircleImageView mAvatarImage;
    @Bind(R.id.nickname)
    TextView mNicknameView;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
//    @Bind(R.id.trends_list)
//    SuperRecyclerView mRecycler;

    private RtFriendResAdapter mAdapter;

    // button area
    @Bind(R.id.btn_add_friend)
    ImageButton mAddFriend;
    @Bind(R.id.btn_added_friend)
    ImageButton mAddedFriend;
    @Bind(R.id.btn_message_disable)
    ImageButton mMsgDisable;
    @Bind(R.id.btn_message_enable)
    ImageButton mMsgEnable;

    // function area
    @Bind(R.id.mileage)
    TextView mMileage;
    @Bind(R.id.drive)
    TextView mDrive;
    @Bind(R.id.trends)
    TextView mTrends;

    // location
    @Bind(R.id.location)
    TextView mLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.friend_activity_user_detail);

        ButterKnife.bind(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle == null || bundle.isEmpty()) {
            finish();
            return;
        }

        mToolbar.setTitleTextColor(getResources().getColor(R.color.white));
        setSupportActionBar(mToolbar);
        actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
        mToolbar.setNavigationIcon(R.mipmap.ic_back);


//        mBundleRecyclerViewState = new Bundle();

        collapsingToolbarLayout.setBackgroundColor(getResources().getColor(R.color.app_primary_color));
        collapsingToolbarLayout.setStatusBarScrimColor(getResources().getColor(R.color.app_primary_color));
        collapsingToolbarLayout.setContentScrimColor(getResources().getColor(R.color.app_primary_color));
        collapsingToolbarLayout.setTitleEnabled(false);
        collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER_HORIZONTAL);
        collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(R.color.transparent));
        collapsingToolbarLayout.setCollapsedTitleTextColor(getResources().getColor(R.color.white));

//        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        player = getPlayer();
        mAdapter = new RtFriendResAdapter(new ArrayList<RtResource>(), player);
//        mRecycler.setAdapter(mAdapter);
//
//        mRecycler.setupMoreListener(this, 1);

        mAccountId = bundle.getString(LocalConstants.BUNDLE_ACCOUNT_ID);
        initView();
        prepareInitView();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
        }
    }

    @Override
    public void onPause() {
        L.d("saving listview state @ onPause");
        super.onPause();
//        Parcelable listState = mRecycler.getRecyclerView().getLayoutManager().onSaveInstanceState();
//        mBundleRecyclerViewState.putParcelable(KEY_RECYCLER_STATE, listState);
        if (player.isPlaying()) {
            player.pause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();

//        if (mBundleRecyclerViewState != null) {
//            Parcelable listState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
//            mRecycler.getRecyclerView().getLayoutManager().onRestoreInstanceState(listState);
//        }
//
//        if (mAdapter.getItemCount() == 0){
//            currPage = 0;
//            loadData(currPage);
//        }
    }

    private void initView() {
        Fragment fragment = new RtResourceListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Constants.BUNDLE_ARGUMENT_AUTHOR_ID, mAccountId);
        fragment.setArguments(bundle);
        // change the fragment
        FragmentTransaction ftx = getSupportFragmentManager().beginTransaction();
        ftx.replace(R.id.frame_container_user_trends, fragment).commit();

    }

    private void prepareInitView() {
        TrendMember trendMember = PersistUtils.getTrendMember(mAccountId);
        if (trendMember != null){
            Account account = new Account();
            account.mAccountId = mAccountId;
            account.mNickName = trendMember.getNickname();
            account.mAvatar = trendMember.getAvatarUrl();
            account.mGender = Integer.valueOf(trendMember.getGender());
            initView(account);
        } else {
            performGetAccount();
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("accountId", mAccountId);
        RestClient.getRestNormalService().mileageSummaryForAccount(params, new Callback<MileageSummaryResponse>() {
            @Override
            public void success(MileageSummaryResponse mileageSummaryResponse, Response response) {
                if (mileageSummaryResponse.errorCode.equals("0") && mileageSummaryResponse.data != null) {
                    Double mileage = mileageSummaryResponse.data.mileage;
                    Long period = mileageSummaryResponse.data.period;
                    if (mileage != null) {
                        mMileage.setText(NumberUtils.formatNumber(mileage / 1000) + " km");
                    }
                    if (period != null) {
                        CharSequence duration = DateUtils.formatDuration(period.longValue());
                        mDrive.setText(duration);
                    }

                }
            }

            @Override
            public void failure(RetrofitError error) {
                L.e(error);
            }
        });

    }

//    @Override
//    public void onMoreAsked(int numberOfItems, int numberBeforeMore, int currentItemPos) {
//        currPage += 1;
//        loadData(currPage);
//    }

//    private void storeDataToCache(List<RtResource> data) {
//        List<NoSQLEntity<RtResource>> entities = new ArrayList<NoSQLEntity<RtResource>>();
//        for (final RtResource dr : data) {
//            NoSQLEntity<RtResource> entity = new NoSQLEntity<RtResource>(Constants.RT_RESOURCE_BUCKET, dr.id, dr);
//            entities.add(entity);
//        }
//        NoSQL.with(GlobalContext.getGlobalContext()).using(RtResource.class).save(entities);
//    }

//    private void loadDataFromCache() {
//        NoSQL.with(GlobalContext.getGlobalContext()).using(RtResource.class)
//                .bucketId(Constants.RT_RESOURCE_BUCKET)
//                .orderBy(new DataComparator<RtResource>() {
//                    @Override
//                    public int compare(NoSQLEntity<RtResource> lhs, NoSQLEntity<RtResource> rhs) {
//                        RtResource l = lhs.getData();
//                        RtResource r = rhs.getData();
//
//                        return Long.valueOf(r.createDate).compareTo(Long.valueOf(l.createDate));
//                    }
//                })
//                .retrieve(new RetrievalCallback<RtResource>() {
//                    @Override
//                    public void retrievedResults(List<NoSQLEntity<RtResource>> noSQLEntities) {
//                        for (NoSQLEntity<RtResource> entity : noSQLEntities) {
//                            RtResource dr = entity.getData();
//                            mAdapter.append(dr);
//                        }
//                    }
//                });
//    }

    private AudioPlayer getPlayer() {
        if (player != null) {
            if (player.isPlaying())
                player.stop();
        } else {
            player = new AudioPlayer();
        }
        //if everything ok play file
        //in case of any error return from method before (catch)
        return player;
    }

    private void performGetAccount() {
        GetAccountRequest request = new GetAccountRequest();
        request.accountId = mAccountId;
        RestClient.getRestNormalService().accountGet(request, new Callback<GetAccountResponse>() {
                    @Override
                    public void success(GetAccountResponse getAccountResponse, Response response) {
                        Account account = getAccountResponse.account;
                        initView(account);

//                        NoSQLEntity<Account> entity = new NoSQLEntity<Account>(Constants.ACCOUNT_BUCKET, mAccountId, account);
//                        NoSQL.with(GlobalContext.getGlobalContext()).using(Account.class)
//                                .save(entity);
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        L.e(error);
//                        if (error.getKind() == RetrofitError.Kind.NETWORK) {
//                            Toast.makeText(FriendDetailActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
//                        }
                    }
                }

        );
    }

    private void initView(Account account) {
        title = account.mNickName;
        final String avatar = account.mAvatar;
        Picasso.with(GlobalContext.getGlobalContext()).load(avatar).fit().centerInside().into(mAvatarImage);

        mAvatarImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageBrowser(avatar);
            }
        });

        mNicknameView.setText(title);

        //titleView.setText(title);


        LocationUtils.getAddressForAccount(this, account.mLng, account.mLat, mLocation);

        setupButtons();

//        loadLocalData();
    }

    private void imageBrowser(String link) {
        Intent intent = new Intent(this, ImagePagerActivity.class);
        ArrayList<String> links = new ArrayList<>();
        links.add(link);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, links);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, 1);
        startActivity(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    public void onEvent(AcceptFriendEvent event) {
        if (event.fromUserId.equals(mAccountId)) {
            buttonsForFriend();
        }
    }

//    public void onEvent(ReloadRtResourceEvent event){
//        currPage = 0;
//        loadData(currPage);
//    }

    private void setupButtons() {
        if (null == FriendHelper.getInstance().getContactUser(mAccountId)) {
            buttonsNonFriend();
        } else {
            buttonsForFriend();
        }
    }

    private void buttonsNonFriend() {
        mAddFriend.setVisibility(View.VISIBLE);
        mAddedFriend.setVisibility(View.GONE);
        mMsgDisable.setVisibility(View.VISIBLE);
        mMsgEnable.setVisibility(View.GONE);
    }

    private void buttonsForFriend() {
        mAddFriend.setVisibility(View.GONE);
        mAddedFriend.setVisibility(View.VISIBLE);
        mMsgDisable.setVisibility(View.GONE);
        mMsgEnable.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.btn_add_friend)
    void addFriend() {
        AddRequest request = new AddRequest();
        request.mAccountId = AccountUtils.getAccountID();
        request.mContactId = mAccountId;
        RestClient.getRestNormalService().add(request, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (restResponse.mErrorCode.equals("0")) {
                    L.d("add friend sent");
                }
            }

            @Override
            public void failure(RetrofitError error) {
                L.e(error);
            }
        });
        ToastUtils.show(this, getString(R.string.add_friend) + getString(R.string.request_is_sent));
    }

    @OnClick(R.id.btn_message_enable)
    void message() {
        Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
        intent.putExtra(Constant.CHAT_PARAMS_USER_ID, mAccountId);
        intent.putExtra(Constant.CHAT_PARAMS_TYPE, Constant.CHATTYPE_SINGLE);
        startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case MENU_REMOVE_FRIEND: {
                //FriendHelper.getInstance().
            }
            case MENU_ADD_BLACKLIST: {
                addToBlacklist();
                return true;
            }
            case MENU_REMOVE_BLACKLIST: {
//                deleteFromBlacklist();
                return true;
            }
            case R.id.action_settings:
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void addToBlacklist() {
        RestClient.getRestNormalService().rtAddBlacklist(AccountUtils.getAccountID(), new RtBlacklistRequest(mAccountId), new Callback<RtBlacklistResponse>() {
            @Override
            public void success(RtBlacklistResponse rtbResponse, Response response) {
                if (rtbResponse.errorCode.equals("0")) {
                    if (rtbResponse.data != null && !rtbResponse.data.isEmpty()) {
                        List<NoSQLEntity<String>> entities = new ArrayList<NoSQLEntity<String>>();
                        for (String accountId : rtbResponse.data) {
                            NoSQLEntity<String> entity = new NoSQLEntity<String>(
                                    Constants.RT_BLACKLIST_BUCKET, accountId, accountId);
                            entities.add(entity);
                        }
                        NoSQL.with(GlobalContext.getGlobalContext()).using(String.class).save(entities);
                    }
                    // delete all cached data for specific user
                    NoSQL.with(GlobalContext.getGlobalContext()).using(RtResource.class)
                            .bucketId(Constants.RT_RESOURCE_BUCKET)
                            .filter(new DataFilter<RtResource>() {
                                @Override
                                public boolean isIncluded(NoSQLEntity<RtResource> item) {
                                    if (item.getData().accountId.equals(mAccountId)) {
                                        return true;
                                    }
                                    return false;
                                }
                            })
                            .delete();
                    // set more listener null
                    EventBus.getDefault().post(new ReloadRtResourceEvent());
                }
            }

            @Override
            public void failure(RetrofitError error) {
                if (error.getKind() != RetrofitError.Kind.NETWORK) {
                    L.e("addToBlacklist()", error);
                }
            }
        });
    }

//    private void loadLocalData() {
//        NoSQL.with(GlobalContext.getGlobalContext()).using(RtResource.class)
//                .bucketId(Constants.RT_RESOURCE_BUCKET)
//                .filter(new DataFilter<RtResource>() {
//                    @Override
//                    public boolean isIncluded(NoSQLEntity<RtResource> item) {
//                        if (item.getData().accountId.equals(mAccountId)) {
//                            return true;
//                        }
//                        return false;
//                    }
//                })
//                .orderBy(new DataComparator<RtResource>() {
//                    @Override
//                    public int compare(NoSQLEntity<RtResource> lhs, NoSQLEntity<RtResource> rhs) {
//                        RtResource l = lhs.getData();
//                        RtResource r = rhs.getData();
//
//                        return Long.valueOf(r.createDate).compareTo(Long.valueOf(l.createDate));
//                    }
//                })
//                .retrieve(new RetrievalCallback<RtResource>() {
//                    @Override
//                    public void retrievedResults(List<NoSQLEntity<RtResource>> noSQLEntities) {
//                        if (noSQLEntities == null || noSQLEntities.isEmpty()) {
//                            mTrends.setText("0");
//                        } else {
//                            int size = noSQLEntities.size();
//                            mTrends.setText(String.valueOf(size));
//
//                            for (NoSQLEntity<RtResource> entity : noSQLEntities) {
//                                RtResource dr = entity.getData();
//                                mAdapter.append(dr);
//                            }
//                        }
//                    }
//                });
//    }

//    private void loadData(final int page) {
//
//        ResourceListByAccountRequest request = new ResourceListByAccountRequest();
//        request.accountId = AccountUtils.getAccountID();
//        request.authorId = mAccountId;
//        request.pageNumber = String.valueOf(currPage);
//        request.pageSize = String.valueOf(10);
//
//        RestClient.getRestNormalService().rtResourceListByAccount(request, new Callback<RtResourcesList4AccountResponse>() {
//
//            @Override
//            public void success(RtResourcesList4AccountResponse listResponse, Response response) {
//                mRecycler.hideMoreProgress();
//                if (!listResponse.errorCode.equals("0")) {
//                    return;
//                }
//                if (page == 0) {
//                    mAdapter.clear();
//                }
//                long count = listResponse.mData.count;
//                mTrends.setText(String.valueOf(count));
//
//                List<RtResource> reses = listResponse.mData.resources;
//                if (page == 0) {
//                    int size = reses.size();
//                    for (int i = size; i > 0; i--) {
//                        RtResource res = reses.get(i - 1);
//                        mAdapter.appendTop(res);
//                    }
//                } else {
//                    for (RtResource res : reses) {
//                        mAdapter.append(res);
//                    }
//                }
//
//                storeDataToCache(reses);
//            }
//
//            @Override
//            public void failure(RetrofitError error) {
//                mRecycler.hideMoreProgress();
//                if (error.getKind() == RetrofitError.Kind.NETWORK) {
//                    loadDataFromCache();
//                } else {
//                    L.e(error);
//                    Toast.makeText(GlobalContext.getGlobalContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
//    }

    @Override
    public void onBackPressed() {
        finish();
    }
}

